% find x/y shift to minimize error
% hyzhou, 04/24/2019
% Inputs:
%   x_sim: location of simulation points, 1D row vector
%   T_sim: simulated temperatures
%   x_exp: location of experimental data relative to heating point, can
%   have 1 row or 2 rows. If there are 2 rows, we have (x,y) coordinates
%   for the heat gradient case
%   T_exp: experimental results
%   T_exp_err: error bars on experimental results
% Optinal inputs:
%   lb: min x,y search range
%   ub: max x,y search range
% Outputs:
%   shift: two-component vector scaling factor that minimizes weighted least square errors
%   err: err on this fit

function [shift, err] = fit_shift(x_sim, T_sim, x_exp, T_exp, T_exp_err, varargin)
global data_list
data_list = {x_sim, T_sim, x_exp, T_exp, T_exp_err};
x0 = [0,0];
if length(varargin) < 1
    lb = [-5e-6,-5e-6];
end
if length(varargin) < 2
    ub = [5e-6,5e-6];
end
[shift,err] = fmincon(@funmin,x0,[],[],[],[],lb,ub);

function err = funmin(x)
global data_list
if size(data_list{3},1) == 1
    xexp = sqrt((x(1)+data_list{3}).^2+x(2).^2);
else
    xexp = sqrt((x(1)+data_list{3}(1,:)).^2+(x(2)+data_list{3}(2,:)).^2);
end
[~,~,err] = fit_scaling_factor(data_list{1},data_list{2},abs(xexp)',data_list{4},data_list{5});
err = err.rmse;
